import React, { useState, useEffect } from 'react';
import { Form, Input, Select, Button, Space, Tag, Popconfirm, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import { PlusOutlined, EditOutlined, DeleteOutlined, TeamOutlined, BookOutlined, FileTextOutlined } from '@ant-design/icons';
import { FilterCard, TableCard } from '@/components/common';
import { contestService } from '@/services/contestService';
import { Contest, ContestRuleType, ContestStatus, ContestType } from '@/types/contest';
import { CONTEST_STATUS_MAP, CONTEST_RULE_TYPE_MAP, CONTEST_TYPE_MAP, getMappingItem } from '@/utils/mappings';
import dayjs from 'dayjs';
import { useAuthStore } from '@/store/useAuthStore';

const { Option } = Select;

interface ContestListProps {
  isAdmin?: boolean;
}

const ContestList: React.FC<ContestListProps> = ({ isAdmin = false }) => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [contests, setContests] = useState<Contest[]>([]);
  const [form] = Form.useForm();
  const { isAuthenticated } = useAuthStore();

  const urlPrefix = isAdmin ? '/admin/contest' : '/contest';

  const fetchContests = async (values?: any) => {
    try {
      setLoading(true);
      const response = await contestService.getContests({
        keyword: values?.keyword,
        rule_type: values?.rule_type as ContestRuleType,
        status: values?.status as ContestStatus
      });
      if (response.data && Array.isArray(response.data.data)) {
        setContests(response.data.data);
      } else {
        console.error('Invalid response format:', response.data);
        setContests([]);
      }
    } catch (error) {
      console.error('Fetch contests error:', error);
      message.error('获取比赛列表失败');
      setContests([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchContests();
  }, []);

  const handleReset = () => {
    fetchContests();
  };

  const handleDelete = async (id: number) => {
    try {
      const response = await contestService.deleteContest(id);
      console.log('Delete response:', response);
      message.success('删除成功');
      // 强制刷新列表
      await fetchContests(form.getFieldsValue());
      // 如果列表中仍然存在已删除的比赛，手动从列表中移除
      setContests(prevContests => prevContests.filter(contest => contest.id !== id));
    } catch (error) {
      console.error('Delete error:', error);
      message.error('删除失败');
    }
  };

  const getStatusTag = (status: ContestStatus | undefined) => {
    if (!status) {
      return <Tag color="default">未知</Tag>;
    }
    
    const { text, color } = getMappingItem(CONTEST_STATUS_MAP, status);
    return <Tag color={color}>{text}</Tag>;
  };

  const getRuleTypeTag = (ruleType: ContestRuleType | undefined) => {
    if (!ruleType) {
      return <Tag color="default">未知</Tag>;
    }
    
    const { text, color } = getMappingItem(CONTEST_RULE_TYPE_MAP, ruleType);
    return <Tag color={color}>{text}</Tag>;
  };

  const getContestTypeTag = (contestType: ContestType | undefined) => {
    if (!contestType) {
      return <Tag color="default">未知</Tag>;
    }
    
    const { text, color } = getMappingItem(CONTEST_TYPE_MAP, contestType);
    return <Tag color={color}>{text}</Tag>;
  };

  // 根据用户角色和权限定义不同的列
  const getColumns = () => {
    const baseColumns = [
      {
        title: '标题',
        dataIndex: 'title',
        key: 'title',
        render: (text: string, record: Contest) => (
          <a onClick={() => navigate(`${urlPrefix}/${record.id}`)}>{text}</a>
        ),
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        render: (status: ContestStatus) => getStatusTag(status),
      },
      {
        title: '规则类型',
        dataIndex: 'rule_type',
        key: 'rule_type',
        render: (ruleType: ContestRuleType) => getRuleTypeTag(ruleType),
      },
      {
        title: '比赛类型',
        dataIndex: 'contest_type',
        key: 'contest_type',
        render: (contestType: ContestType) => getContestTypeTag(contestType),
      },
      {
        title: '开始时间',
        dataIndex: 'start_time',
        key: 'start_time',
        render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm'),
      },
      {
        title: '结束时间',
        dataIndex: 'end_time',
        key: 'end_time',
        render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm'),
      },
      {
        title: '创建者',
        dataIndex: 'created_by',
        key: 'created_by',
        render: (created_by: { username: string }) => created_by?.username || '-',
      },
    ];

    // 根据用户角色添加操作列
    if (isAdmin) {
      // 管理员操作列
      baseColumns.push({
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        render: (_: any, record: Contest) => (
          <Space size="middle">
            <Button 
              type="link" 
              icon={<EditOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                navigate(`${urlPrefix}/edit/${record.id}`);
              }}
            >
              编辑
            </Button>
            <Button 
              type="link" 
              icon={<BookOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                navigate(`${urlPrefix}/${record.id}/problems`);
              }}
            >
              题目
            </Button>
            <Button 
              type="link" 
              icon={<FileTextOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                navigate(`${urlPrefix}/${record.id}/review`);
              }}
            >
              批阅
            </Button>
            <Popconfirm
              title="确定要删除这个比赛吗？"
              onConfirm={(e) => {
                e?.stopPropagation();
                handleDelete(record.id);
              }}
              onCancel={(e) => e?.stopPropagation()}
            >
              <Button 
                type="link" 
                danger 
                icon={<DeleteOutlined />}
                onClick={(e) => e.stopPropagation()}
              >
                删除
              </Button>
            </Popconfirm>
          </Space>
        ),
      } as any);
    } else {
      // 普通用户操作列
      baseColumns.push({
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        render: (_: any, record: Contest) => (
          <Space size="middle">
            <Button 
              type="primary" 
              icon={<TeamOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                navigate(`${urlPrefix}/${record.id}`);
              }}
              disabled={record.status === '-1'} // 已结束的比赛禁用按钮
            >
              参加比赛
            </Button>
          </Space>
        ),
      } as any);
    }

    return baseColumns;
  };

  return (
    <div>
      <FilterCard
        pageTitle="比赛列表"
        titleIcon={<TeamOutlined />}
        form={form}
        onFinish={fetchContests}
        onReset={handleReset}
        extra={
          isAdmin ? (
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={() => navigate(`${urlPrefix}/create`)}
            >
              创建比赛
            </Button>
          ) : null
        }
      >
        <Form.Item name="keyword" label="关键词">
          <Input placeholder="搜索比赛标题" style={{ width: 200 }} />
        </Form.Item>
        <Form.Item name="rule_type" label="规则类型">
          <Select style={{ width: 120 }} allowClear>
            <Option value="ACM">ACM</Option>
            <Option value="OI">OI</Option>
          </Select>
        </Form.Item>
        <Form.Item name="status" label="状态">
          <Select style={{ width: 120 }} allowClear>
            <Option value="1">未开始</Option>
            <Option value="0">进行中</Option>
            <Option value="-1">已结束</Option>
          </Select>
        </Form.Item>
      </FilterCard>

      <TableCard
        tableProps={{
          columns: getColumns(),
          dataSource: contests,
          rowKey: 'id',
          loading: loading,
          onRow: (record: Contest) => ({
            onClick: () => navigate(`${urlPrefix}/${record.id}`),
          }),
        }}
      />
    </div>
  );
};

export default ContestList; 